//
//  TouchHandler.m
//  PortmanTouch
//
//  Created by cclaan on 11/4/09.
//  Copyright 2009 __MyCompanyName__. All rights reserved.
//

#import "TouchHandler.h"

#import "TouchGesture.h"




@implementation TouchHandler

@synthesize parentView;

- (id) init
{
	self = [super init];
	if (self != nil) {
		
		gestures = [[NSMutableArray alloc] init];
		
		recognizer = [[GestureRecognizer alloc] init];
		
	}
	return self;
}


-(void) render {
	

	glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    glOrthof(0.0f, 320.0f, 480.0f, 0.0f, -1.0f, 1.0f);
	
    glMatrixMode(GL_MODELVIEW);
	glLoadIdentity();

	
	
    glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
    glClear(GL_COLOR_BUFFER_BIT);
    
	
	
	for ( TouchGesture * gesture in gestures ) {
		
		
		[gesture render];
		
		
	}
	
	
	
}



- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{	
	
	//NSLog(@"Touches began: %i " , [touches count] );
	//NSLog(@"Touches BEGAN: %i " , [[event allTouches] count] );
	
	for ( UITouch * touch in touches )
	{
		
		TouchGesture * g = [[TouchGesture alloc] init];
		[gestures addObject:g];
		
		
		CGPoint p = [touch locationInView:parentView];
		[g addPoint:p];
		
		g.touch = touch;
		
		
	}
	

}

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
	
	//NSLog(@"Touches moved: %i " , [touches count] );
	//NSLog(@"Touches MOVED event: %i " , [[event allTouches] count] );
	
	for ( UITouch * touch in touches )
	{
		
		/*
		int indexOfTouch = 0;
		
		if ( [gestures count] > 1 ) {
			
			for ( UITouch * t in [event allTouches] ) {
				
				if ( t == touch ) break;
				indexOfTouch ++;
				
			}
			
		} 
		
		TouchGesture * g = (TouchGesture*)[gestures objectAtIndex:indexOfTouch];
		CGPoint p = [touch locationInView:parentView];
		[g addPoint:p];
		*/
		
		for ( TouchGesture * g in gestures ) {
			if ( g.touch == touch ) {
				CGPoint p = [touch locationInView:parentView];
				[g addPoint:p];
				break;
			}
		}
		
	}
	
}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
	
	[self endTouches:touches withEvent:event];
	
}
- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event
{
	
	NSLog(@"Cancelled");
	[self endTouches:touches withEvent:event];
	
}


-(void) endTouches:(NSSet *) touches withEvent:(UIEvent*) event {
	
	NSLog(@"Touches ended: %i " , [[event allTouches] count] );
	
	for ( UITouch * touch in touches )
	{
		/*
		int indexOfTouch = -1;
		
		if ( [gestures count] > 1 ) {
			
			for ( UITouch * t in [event allTouches] ) {
				
				if ( t == touch ) break;
				
				indexOfTouch ++;
				
			}
			
		} else if ( [gestures count] == 1 ) {
			indexOfTouch = 0;
		}
		
		if ( indexOfTouch >= 0 ) {
			TouchGesture * g = (TouchGesture*)[gestures objectAtIndex:indexOfTouch];
			[gestures removeObject:g];
		}*/
		
		
		for ( TouchGesture * g in gestures ) {
			
			if ( g.touch == touch ) {
				
				[recognizer recognizeGesture:g];
				
				[gestures removeObject:g];
				
				break;
				
			}
		}
		
		
		
	}
	
}




@end
